import getSqliteClient from './init';
import {
    EmojiPackItemUpdateType,
    UserEmojiPackType,
    UserEmojiPackItemCreateType,
    UserEmojiPackItemType, UserEmojiPackUpdateType, UserEmojiPackCreateType,
} from "@/types/user-emoji";

const db = getSqliteClient();

/**
 * 插入表情包项
 * @param item 表情包项数据
 */
export const insertEmojiPackageItem = async (item: UserEmojiPackItemCreateType): Promise<void> => {
    const query = `
    INSERT INTO user_emoji_package_item_cache (
      emoji_pack_item_id, owner_id, file_path, server_url,server_file_id, sort_order, create_time, update_time
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `;
    await db.runAsync(query, [
        item.id,
        item.userId,
        item.filePath,
        item.serverUrl,
        item.fileId,
        item.sortOrder,
        item.createTime,
        item.updateTime,
    ]);
};

/**
 * 查询用户表情包项
 * @param userId
 */
export const getEmojiPackageItems = async (userId: string): Promise<UserEmojiPackItemType[]> => {
    const query = `
    SELECT * FROM user_emoji_package_item_cache WHERE owner_id = ? ORDER BY sort_order DESC, create_time ASC
  `;
    const result = await db.getAllAsync(query, [userId]);
    if (!result) {
        return null;
    }
    return result.map(mapToUserEmojiPackItemType);
};

/**
 * 查询用户表情包项
 * @param id 表情包项ID
 * @param userId
 */
export const getEmojiPackageItemById = async (id : string, userId: string): Promise<UserEmojiPackItemType> => {
    const query = `
    SELECT * FROM user_emoji_package_item_cache WHERE emoji_pack_item_id = ? AND owner_id = ? ORDER BY sort_order ASC , create_time DESC
  `;
    const result = await db.getFirstAsync(query, [id,userId]);
    return result ? mapToUserEmojiPackItemType(result) : null;
};

/**
 * 更新表情包项
 * @param update 更新数据
 */
export const updateEmojiPackageItem = async (update: EmojiPackItemUpdateType): Promise<void> => {
    const fields = []
    const values = []
    if (update.sortOrder !== undefined) {
        fields.push('sort_order = ?');
        values.push(update.sortOrder);
    }

    const query = `
    UPDATE user_emoji_package_item_cache SET ${fields} WHERE emoji_pack_item_id = ?
  `;
    await db.runAsync(query, [...values, update.id]);
};

/**
 * 删除表情包项
 * @param userId 用户ID
 * @param itemId 表情包项ID
 */
export const deleteEmojiPackageItem = async (itemId: string, userId: string): Promise<void> => {
    const query = `
    DELETE FROM user_emoji_package_item_cache WHERE owner_id = ? AND emoji_pack_item_id = ?
  `;
    console.log(`Deleting emoji pack item with ID: ${itemId} for user: ${userId}`);
    await db.runAsync(query, [userId, itemId]).then(r => {
        console.log(r)
    }).catch(e => {
        console.error(`Failed to delete emoji pack item with ID: ${itemId} for user: ${userId}`, e);
    });
};

function mapToUserEmojiPackItemType(item: any): UserEmojiPackItemType {
    return {
        id: item.emoji_pack_item_id,
        fileUrl: item.server_url,
        filePath: item.file_path,
        fileId: item.server_file_id,
        serverUrl: item.server_url, // Assuming serverUrl is the same as fileUrl
        sortOrder: item.sort_order,
        createTime: item.create_time,
        updateTime: item.update_time,
    };
}

/**
 * 查询用户表情包
 * @param userId 用户ID
 */
export const getUserEmojiPackage = async (userId: string): Promise<UserEmojiPackType> => {
    const query = `
    SELECT * FROM user_emoji_package WHERE owner_id = ? ORDER BY create_time DESC
  `;
    const result = await db.getFirstAsync(query, [userId]);
    return result ? mapToUserEmojiPack(result) : null;
};

/**
 * 更新用户表情包
 * @param update 更新数据
 */
export const updateUserEmojiPackage = async (update: UserEmojiPackUpdateType): Promise<void> => {
    const query = `
    UPDATE user_emoji_package SET create_time = ? , update_time = ? WHERE owner_id = ?
  `;
    await db.runAsync(query, [update.createTime, update.updateTime, update.ownerId]);
};

/**
 * 创建用户表情包
 * @param create 创建数据
 */
export const createUserEmojiPackage = async (create: UserEmojiPackCreateType): Promise<void> => {
    const query = `
    INSERT INTO user_emoji_package (owner_id, create_time, update_time)
    VALUES (?, ?, ?)
  `;
    await db.runAsync(query, [create.ownerId, create.createTime, create.updateTime]);
};


function mapToUserEmojiPack(item: any): UserEmojiPackType {
    return {
        createTime: item.create_time,
        updateTime: item.update_time,
    };
}